package Zookeeper.case3;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class CuratorLockTest {
    public static void main(String[] args) {

        // 创建分布式锁 1
        InterProcessLock lock1 = new InterProcessMutex(getCuratorFramework(), "/locks");

        // 创建分布式锁 2
        InterProcessLock lock2 = new InterProcessMutex(getCuratorFramework(), "/locks");

        // 创建线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    lock1.acquire();
                    System.out.println("线程 1 获得锁");
                    lock1.acquire();
                    System.out.println("线程 1 再次获得锁");

                    Thread.sleep(5 * 1000);

                    lock1.release();
                    System.out.println("线程 1 释放锁");
                    lock1.release();
                    System.out.println("线程 1 再次释放锁");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    lock2.acquire();
                    System.out.println("线程 2 获得锁");
                    lock2.acquire();
                    System.out.println("线程 2 再次获得锁");

                    Thread.sleep(5 * 1000);

                    lock2.release();
                    System.out.println("线程 2 释放锁");
                    lock2.release();
                    System.out.println("线程 2 再次释放锁");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

            }
        }).start();
    }

    private static CuratorFramework getCuratorFramework() {

        ExponentialBackoffRetry retry = new ExponentialBackoffRetry(3000, 1);

        CuratorFramework client = CuratorFrameworkFactory.builder().connectString("192.168.130.133:2181")
                .sessionTimeoutMs(10000)
                .connectionTimeoutMs(2000)
                .retryPolicy(retry).build();

        // 启动客户端
        client.start();
        System.out.println("zookeeper 启动成功");

        return client;
    }
}
